package cn.ccew.common.utils;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SendMailDemo {
	private static final String YourMail = "lxj08193@163.com";
	private static final String ToMail = "867424981@qq.com";

	public static void main(String[] args) {
		SendMailDemo.attachedFileMail();
	}

	public static void simpleMail() {
		try {
			// 使用Spring提供的MailSender
			//ApplicationContext app = new ClassPathXmlApplicationContext("spring-mail.xml");

			JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
			// 设定邮件服务器地址
			mailSender.setHost("smtp.163.com");
			// 设置邮件服务器端口
			mailSender.setPort(25); // 可省略
			// sender.set
			mailSender.setDefaultEncoding("utf-8");
			mailSender.setUsername("lxj08193@163.com");
			mailSender.setPassword("sbiwvfhp1212");
			Properties prop = new Properties();
			//<!-- 是否进行身份认证 -->
			prop.put("mail.smtp.auth", true);
			//<!-- 是否采用SSL登录 -->
			prop.put("mail.smtp.starttls.enable", true);

			mailSender.setJavaMailProperties(prop);
			
			
			// JavaMailSender mailSender = (JavaMailSender)
			// app.getBean("mailSender");
			// 创建一个纯文本邮件
			SimpleMailMessage mail = new SimpleMailMessage();
			// 发送方
			mail.setFrom(YourMail);
			// 接收人
			mail.setTo(ToMail);
			// 邮件标题
			mail.setSubject("测试简单邮件发送");
			// 内容
			mail.setText("测试使用SpringMailSender发送邮件");
			// 发送
			mailSender.send(mail);
			System.out.println("邮件发送成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//ynjob_gov@163.com   ynjob_gov_admin
	}

	public static void attachedFileMail() {
		try {
			ApplicationContext app = new ClassPathXmlApplicationContext("cn/config/spring-base.xml");
			JavaMailSender mailSender = (JavaMailSender) app.getBean("mailSender");
			MimeMessage mime = mailSender.createMimeMessage();
			// multipart模式 为true时发送附件 可以设置html格式
			MimeMessageHelper messageHelper = new MimeMessageHelper(mime, true, "utf-8");
			// 发送方
			messageHelper.setFrom(YourMail);
			// 接收人
			messageHelper.setTo(ToMail);
			// 邮件标题
			messageHelper.setSubject("测试包含附件邮件发送");
			// true 表示启动HTML格式的邮件
			messageHelper.setText("<html><head></head><body><h3>你好：附件中有惊喜,请查收！</h3></body></html>", true);
			// 附件
			// FileSystemResource file = new FileSystemResource(new
			// File("D:\\a.xls"));
			// messageHelper.addAttachment("a.xls", file);
			// 发送
			mailSender.send(mime);
			System.out.println("邮件发送成功!");
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
}
